package com.netty.client.socket;

import com.netty.handler.LoggingHandler;
import com.netty.model.proto.SentBodyProto;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ImSocketClient {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private ProtobufDecoder decoder = new ProtobufDecoder(SentBodyProto.Model.getDefaultInstance());
    private ProtobufEncoder encoder = new ProtobufEncoder();

    private String url = "127.0.0.1";
    private Integer port = 23456;

    private ImSocketClientHandler imSocketClientHandler;

    public void startClient() {
        EventLoopGroup workGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(workGroup);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                ChannelPipeline pipeline = socketChannel.pipeline();
                pipeline.addLast(new LoggingHandler());
                // 主要用于处理大数据流，比如一个1G大小的文件如果你直接传输肯定会撑暴jvm内存的; 增加之后就不用考虑这个问题了
                pipeline.addLast(new ChunkedWriteHandler());

                pipeline.addLast("frameDecoder", new ProtobufVarint32FrameDecoder());
                pipeline.addLast(decoder);
                pipeline.addLast("frameEncoder", new ProtobufVarint32LengthFieldPrepender());
                pipeline.addLast(encoder);
                pipeline.addLast("handler",new SocketClientHandler(imSocketClientHandler));
            }
        });
        ChannelFuture connect = bootstrap.connect(url, port);

        connect.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture arg0){
                if (connect.isSuccess()) {
                    logger.info("==========================success==========================");
                } else {
                    logger.info("==========================error==========================");
                    connect.cause().printStackTrace();
                    restartClient();
                }
            }
        });
    }

    //5秒钟后自动重连
    public void restartClient(){
        try {
            Thread.sleep(5000);
            startClient();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public ImSocketClient(ImSocketClientHandler imSocketClientHandler) {
        this.imSocketClientHandler = imSocketClientHandler;
    }
    public ImSocketClient(String url, Integer port,ImSocketClientHandler imSocketClientHandler) {
        this.url = url;
        this.port = port;
        this.imSocketClientHandler = imSocketClientHandler;
    }

}
